<!--

@file: DelEmptyProperty.vue
@author: pan
-->
<script setup lang="ts">
import { cloneDeep } from 'lodash-unified'
const oriObj = {
  name: '张三',
  remark: '',
  age: undefined,
  male: 0,
  other: '年后',
  a: 1,
  parent: {},
  obj: { test: 0 },
  obj2: { good: [] },
  schoolInfo: {
    name: '',
  },
  book: {
    name: undefined,
  },
  friends: [
    {
      name: '',
    },
  ],
  hobby: [],
}
const newObj = cloneDeep(oriObj)
compactObj(newObj, isEmpty)
/**
 * 去除对象中所有符合条件的对象
 * @param {Object} obj 来源对象
 * @param {Function} fn 函数验证每个字段
 */
function compactObj(obj: Object, fn: (p: any) => boolean) {
  for (var i in obj) {
    if (typeof obj[i] === 'object') {
      compactObj(obj[i], fn)
    }
    if (fn(obj[i])) {
      delete obj[i]
    }
  }
}

// 删除空对象 删除'', null, undefined
function isEmpty(foo: any) {
  if (typeof foo === 'object') {
    for (var i in foo) {
      return false
    }
    return true
  } else {
    return foo === '' || foo === null || foo === undefined
  }
}
</script>

<template>
  <div>
    <div>原始对象: {{ oriObj }}</div>
    <br />
    <div>删空对象: {{ newObj }}</div>
  </div>
</template>

<style lang="scss" scoped></style>
